//
//  NDWebRepresentable.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/11/1.
//

import SwiftUI
import WebKit

struct NDWebRepresentable: UIViewRepresentable {
    let urlString: String?
    @ObservedObject var viewModel: NDWebViewModel
    var navManager: Binding<NavigationViewManager>
    
    func makeUIView(context: Context) -> WKWebView {
        let config = WKWebViewConfiguration()
        let userContentController = WKUserContentController()
        
        // 添加消息处理器
        let messageHandler = context.coordinator
        userContentController.add(messageHandler, name: "pirevidenceacious")
        userContentController.add(messageHandler, name: "charge")
        userContentController.add(messageHandler, name: "trud")
        userContentController.add(messageHandler, name: "phenoality")
        userContentController.add(messageHandler, name: "frugcy")
        userContentController.add(messageHandler, name: "productionence")
        
        config.userContentController = userContentController
        
        let webView = WKWebView(frame: .zero, configuration: config)
        webView.navigationDelegate = context.coordinator
        webView.uiDelegate = context.coordinator
        
        viewModel.setWebView(webView)
        
        return webView
    }
    
    func updateUIView(_ uiView: WKWebView, context: Context) {
        // 如果需要重新加载URL，可以在这里处理
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self, navManager: navManager.wrappedValue)
    }
    
    class Coordinator: NSObject, WKScriptMessageHandler, WKNavigationDelegate, WKUIDelegate {
        let parent: NDWebRepresentable
        let navManager: NavigationViewManager
        
        init(_ parent: NDWebRepresentable, navManager: NavigationViewManager) {
            self.parent = parent
            self.navManager = navManager
            super.init()
        }
        
        // MARK: - WKScriptMessageHandler
        func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
            parent.viewModel.handleJavaScriptMessage(message, navManager: navManager)
        }
        
        // MARK: - WKNavigationDelegate
        func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
            parent.viewModel.updateProgress(0.1)
        }
        
        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            parent.viewModel.updateProgress(1.0)
            parent.viewModel.updateNavigationState(canGoBack: webView.canGoBack)
            parent.viewModel.updateNavigationTitle(webView.title ?? "")
        }
        
        func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
            parent.viewModel.updateProgress(1.0)
        }
        
        func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
            decisionHandler(.allow)
            
            if let url = navigationAction.request.url {
                print("用户点击了链接: \(url.absoluteString)")
            }
        }
        
        // MARK: - 进度监听
        override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
            if keyPath == #keyPath(WKWebView.estimatedProgress),
               let webView = object as? WKWebView {
                parent.viewModel.updateProgress(webView.estimatedProgress)
            }
        }
    }
}
